<template>
  <!-- 模板内容不变 -->
  <div class="person-list-drawer">
    <!-- 搜索表单 -->
    <el-form :inline="true" class="search-form">
      <el-form-item label="身份证号">
        <el-input clearable v-model="queryParams.idcard" placeholder="请输入身份证号" />
      </el-form-item>
      <el-form-item label="护照号码">
        <el-input clearable v-model="queryParams.passportNumber" placeholder="请输入护照号码" />
      </el-form-item>
      <el-form-item label="人员分类" prop="groupId">
        <MemberGroupSelect v-model="queryParams.groupId" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-checkbox
          v-model="queryParams.onlyWarn"
          label="只看已选"
          @change="handleSearch"
        />
      </el-form-item>
    </el-form>

    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="personData"
      style="width: 100%"
      row-key="id"
      @selection-change="handleSelectionChange"
      :row-class-name="tableRowClassName"
    >
      <!-- 表格列定义不变 -->
      <el-table-column type="selection" width="55" :reserve-selection="true"/>
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="paperNumber" label="证件号码" width="180" />
      <el-table-column label="证件类型" width="180" align="center">
        <template #default="{ row }">
          <div class="id-type-container">
            <el-tooltip
              :content="row.foreigner === 1 ? '护照' : '身份证'"
              placement="top"
            >
              <component
                :is="row.foreigner === 1 ? PassportIcon : IdCardIcon"
                :class="row.foreigner === 1 ? 'passport-icon' : 'idcard-icon'"
                style="width: 18px; height: 18px;"
              />
            </el-tooltip>
            <span>
              {{ row.foreigner === 1 ? '护照' : '身份证' }}
            </span>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="fetchPersonList(queryParams.warnConfigId)"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, defineProps, defineEmits, onMounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import * as UserApi from '@/api/member/user'
import { Document, Postcard } from '@element-plus/icons-vue'
import { WarnConfigPersonRelationApi } from "@/api/member/warnconfigpersonrelation";
import Pagination from '@/components/Pagination/index.vue';
import MemberGroupSelect from "@/views/member/group/components/MemberGroupSelect.vue";

// 图标别名
const PassportIcon = Document
const IdCardIcon = Postcard

const props = defineProps({
  warnConfigId: {
    type: String,
    required: true,
    default: ''
  },
  visible: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['confirm', 'cancel'])

// 定义人员类型接口
interface Person {
  id: number
  name: string
  paperNumber: string
  foreigner: number
  isWarnSetting: boolean
  remark?: string
  tagNames?: string[]
}

// 响应式数据
const personData = ref<Person[]>([])
const loading = ref(false)
const total = ref(0)
const selectedPersons = ref<Person[]>([])
const tableRef = ref()

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 15,
  name: undefined,
  idcard: undefined,
  passportNumber: undefined,
  onlyWarn: false,
  groupId: null,
  warnConfigId: undefined as string | undefined
})

// 初始化标志位
const isInitializing = ref(false)

// 监听抽屉显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    fetchPersonList()
  } else {
    clearSelectionState()
  }
})

// 改进的清空选中状态方法：临时启用初始化标志位
const clearSelectionState = () => {
  // 关键：清空前设置标志位，避免触发后台请求
  isInitializing.value = true

  // 清空表格选中状态
  tableRef.value?.clearSelection()
  // 重置选中人员数组
  selectedPersons.value = []

  // 延迟重置标志位，确保清空操作触发的事件已处理
  setTimeout(() => {
    isInitializing.value = false
  }, 0)
}

// 获取人员列表，使其可以接收warnConfigId参数（可选）
const fetchPersonList = async (warnConfigId?: string) => {
  try {
    // 清空状态
    clearSelectionState()

    loading.value = true
    // 优先使用传入的ID，如果没有则使用props中的ID
    const currentWarnConfigId = warnConfigId;
    queryParams.warnConfigId = currentWarnConfigId;

    console.log('使用的warnConfigId:', currentWarnConfigId)
    console.log('查询参数:', queryParams)

    const res = await UserApi.getWarnPage(queryParams)
    personData.value = res.list
    total.value = res.total

    await nextTick()
    isInitializing.value = true

    // 设置选中状态
    personData.value.forEach(row => {
      if (row.isWarnSetting) {
        tableRef.value?.toggleRowSelection(row, true)
      }
    })

    selectedPersons.value = personData.value.filter(row => row.isWarnSetting)

    await nextTick()
    isInitializing.value = false
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.pageNo = 1
  fetchPersonList(queryParams.warnConfigId)
}

// 处理选择变化
const handleSelectionChange = async (selection: Person[]) => {
  // 初始化阶段或清空状态时不执行后台操作
  if (isInitializing.value) {
    return
  }

  const prevSelectedSnapshot = [...selectedPersons.value]
  const prevSelectedIds = new Set(prevSelectedSnapshot.map(p => p.id))
  const currentSelectedIds = new Set(selection.map(p => p.id))

  const toAdd = selection.filter(p => !prevSelectedIds.has(p.id))
  const toRemove = prevSelectedSnapshot.filter(p => !currentSelectedIds.has(p.id))

  if (toAdd.length === 0 && toRemove.length === 0) {
    return
  }

  try {
    // 新增关联
    if (toAdd.length > 0) {
      await WarnConfigPersonRelationApi.batchCreateCasePersonRelation({
        warnConfigId: props.warnConfigId,
        personIdList: toAdd.map(p => p.id)
      })
      toAdd.forEach(person => {
        const target = personData.value.find(item => item.id === person.id)
        if (target) target.isWarnSetting = true
      })
    }

    // 移除关联
    if (toRemove.length > 0) {
      await Promise.all(
        toRemove.map(person =>
          WarnConfigPersonRelationApi.deleteCasePersonRelation(
            props.warnConfigId,
            person.id
          )
        )
      )
      toRemove.forEach(person => {
        const target = personData.value.find(item => item.id === person.id)
        if (target) target.isWarnSetting = false
      })
    }

    selectedPersons.value = [...selection]
    ElMessage.success('操作成功')

  } catch (error: any) {
    console.error('API调用失败详情:', error)
    ElMessage.error(`操作失败: ${error.response?.data?.msg || '未知错误'}`)

    // 恢复选中状态
    tableRef.value?.clearSelection()
    prevSelectedSnapshot.forEach(row => {
      tableRef.value?.toggleRowSelection(row, true)
    })
  }
}

// 行样式
const tableRowClassName = ({ row }: { row: Person }) => {
  return row.isWarnSetting ? 'is-case-row' : ''
}

defineExpose({ fetchPersonList });
onMounted(fetchPersonList)
</script>

<style scoped>
/* 样式不变 */
.person-list-drawer {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-form {
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 16px;
}

.id-type-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.passport-icon {
  color: #1890ff;
}

.idcard-icon {
  color: #52c41a;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 16px !important;
  margin-bottom: 12px !important;
}

:deep(.el-form--inline .el-form-item:last-child) {
  margin-right: 0 !important;
}

:deep(.el-checkbox) {
  margin-top: 4px;
}
</style>
